import axios, { AxiosError, AxiosInstance, AxiosResponse, InternalAxiosRequestConfig } from 'axios';
import router from '@/config/router/index.ts';
import { loginPath } from '@/config/config.ts';
import type { JsonResultProps } from '#/JsonResult.d.ts';
import { NavigationFailure } from 'vue-router';
const axiosInstance: AxiosInstance = axios.create({
	timeout : 240000,
	baseURL : '/api',
	headers : {
		get    : {
			'Content-Type' : 'application/x-www-form-urlencoded;charset=UTF-8'
		},
		post   : {
			'Content-Type' : 'application/json;charset=UTF-8'
		},
		put    : {
			'Content-Type' : 'application/json;charset=UTF-8'
		},
		delete : {
			'Content-Type' : 'application/json;charset=UTF-8'
		},
		patch  : {
			'Content-Type' : 'application/json;charset=UTF-8'
		}
	}
});
// 添加错误拦截器
const errorHandler = (error: AxiosError) => {
	return Promise.reject(error);
};
// 添加请求拦截器
axiosInstance.interceptors.request.use(
	(config: InternalAxiosRequestConfig) => {
		// 在第一次请求的时候(登录),是不会拥有x-auth-token的,必须第一次请求过后服务器才会分配一个
		// 每次请求/user/login地址的时候直接清空掉x-auth-token
		if ('/auth/login' === config['url']) {
			delete config['headers']!['x-auth-token'];
		} else {
			config['headers']!['x-auth-token'] = sessionStorage.getItem('x-auth-token');
		}
		return config;
	}, errorHandler);
// 添加响应拦截器
axiosInstance.interceptors.response.use(
	(response: AxiosResponse<any, any>): any | JsonResultProps<any> => {
		if (200 === response['status']) {
			if (401 === response['data'].code) {
				if (loginPath === router.currentRoute.value.fullPath) {
					// 当前就是登录页,不跳路由展示提示
					return response['data'] as JsonResultProps<any>;
				} else {
					// 当前不是登录页,跳路由并展示提示
					router.replace(loginPath).then((fail: NavigationFailure | void | undefined): JsonResultProps<any> => {
						// console.warn(fail);
						return response['data'] as JsonResultProps<any>;
					}).catch((error: any): void => {
						console.error(error);
					});
				}
			}
			// 每次获取服务器的响应的时候都需要将x-auth-token(无论认证与否)存放到请求的head中
			// 如果存在的话才放入sessionStorage中
			// x-auth-token
			// TestMock-x-auth-token
			if (response['headers']['x-auth-token']) {
				sessionStorage.setItem('x-auth-token', response.headers['x-auth-token']);
			}
			return response['data'] as AxiosResponse;
		}
		return response['data'] as AxiosResponse<any, any>;
	}, errorHandler);
export default axiosInstance;